package com.lmmob.autotest.uitest.controls;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class RadioButtonGroup extends Control implements ValueSettable {
    private String name;

    public RadioButtonGroup(String name, WebDriver webDriver) {
        super(webDriver);
        this.name = name;
    }

    @Override
    protected String getSelfQuery() {
        return String.format(".query(\"radiogroup[fieldLabel='%s']\")[0]", name);
    }

    @Override
    protected String getName() {
        return this.name;
    }

    public void setValue(String value) {
        String id = getRadioButtonId(value);
        if (StringUtils.isNotBlank(id)) {
            WebElement container = findElement(By.id(id));
            container.findElement(By.tagName("input")).click();
        }
    }

    private String getRadioButtonId(String value) {
        try {
            return (String) runScript("return " + this.getQuery() + String.format(".query(\"[boxLabel='%s']\")[0].id", value));
        } catch (Exception e) {
            Long itemsCount = (Long) runScript("return " + this.getQuery() + ".items.items.length");
            for (int i = 0; i < itemsCount; ++i) {
                String boxLabel = (String) runScript("return " + this.getQuery() + String.format(".items.items[%s].boxLabel", i));
                if (boxLabel.contains(value)) {
                    return (String) runScript("return " + this.getQuery() + String.format(".items.items[%s].id", i));
                }
            }
            return StringUtils.EMPTY;
        }
    }

    public void verifyValue(String expected) {
        String actual = getCheckedValue().trim();
        assertThat(String.format("RadioButtonGroup[name='%s']", this.name), actual, is(expected));
    }

    private String getCheckedValue() {
        Long len = (Long) runScript("return " + this.getQuery() + ".items.items.length");
        for (int i = 0; i < len; ++i) {
            Boolean checked = (Boolean) runScript("return " + this.getQuery() + String.format(".items.items[%s].checked", i));
            if (checked) {
                return (String) runScript("return " + this.getQuery() + String.format(".items.items[%s].boxLabel", i));
            }
        }
        return StringUtils.EMPTY;
    }
}
